package com.cherry.i18n.core;

import com.cherry.i18n.config.properties.I18nProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 区域解析器：从请求头中解析出区域标识
 *
 * @author sinbad.cheng
 * @since 2022-01-10
 */
public class CherryAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver {

    private final I18nProperties i18nProperties;

    public CherryAcceptHeaderLocaleResolver(I18nProperties i18nProperties) {
        this.i18nProperties = i18nProperties;
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String localeHeader = i18nProperties.getLocaleHeader();
        if (StringUtils.isEmpty(localeHeader) || "Accept-Language".equalsIgnoreCase(localeHeader)) {
            return super.resolveLocale(request);
        }

        String localeValue = request.getHeader(localeHeader);
        if (StringUtils.isEmpty(localeValue)) {
            return super.resolveLocale(request);
        }

        localeValue = StringUtils.replace(localeValue, "_", "-");
        return Locale.forLanguageTag(localeValue);
    }

}